package com.sts.transform.function;

import cn.hutool.core.util.NumberUtil;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDecimal;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

/**
 * @author lsl
 * @since 2025年07月09日 19:58
 */
public class RoundFunction extends AbstractFunction {

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        Number value = FunctionUtils.getNumberValue(arg1, env);
        Number scale = FunctionUtils.getNumberValue(arg2, env);
        return new AviatorDecimal(NumberUtil.round(new BigDecimal(String.valueOf(value.doubleValue())), scale.intValue(), RoundingMode.HALF_UP));
    }

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
        Number value = FunctionUtils.getNumberValue(arg1, env);
        Number scale = FunctionUtils.getNumberValue(arg2, env);
        Number mode = FunctionUtils.getNumberValue(arg3, env);
        return new AviatorDecimal(NumberUtil.round(new BigDecimal(String.valueOf(value.doubleValue())), scale.intValue(), RoundingMode.valueOf(mode.intValue())));
    }

    @Override
    public String getName() {
        return "round";
    }
}
